package com.bby.common.utils;

import com.bby.common.model.RunningStatus;
import com.sun.management.OperatingSystemMXBean;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class SystemMonitor {

    static Map<String,String> infoMap =new HashMap<>();
    static Properties props =System.getProperties();
    static {
        init();
    }
    static void init(){
        String ip = "";
        String hostName = "";
        try {
            InetAddress addr =InetAddress.getLocalHost();
            ip =addr.getHostAddress();
            hostName =addr.getHostName();
        } catch (UnknownHostException e) {
        }
        Runtime r =Runtime.getRuntime();
        Map<String,String> map =System.getenv();
        String userName =map.get("USERNAME");// 获取用户名
        String computerName =map.get("COMPUTERNAME");// 获取计算机名
        String userDomain =map.get("USERDOMAIN");// 获取计算机域名
        infoMap.put("用户名",userName);
        infoMap.put("计算机名",computerName);
        infoMap.put("计算机域名",userDomain);
        infoMap.put("本地ip地址",ip);
        infoMap.put("本地主机名",hostName);
        infoMap.put("JVM可以使用的总内存", String.valueOf(r.totalMemory()));
        infoMap.put("JVM可以使用的剩余内存", String.valueOf(r.freeMemory()));
        infoMap.put("JVM可以使用的处理器个数", String.valueOf(r.availableProcessors()));
        infoMap.put("Java的运行环境版本 ",props.getProperty("java.version"));
        infoMap.put("Java的安装路径 ",props.getProperty("java.home"));
        infoMap.put("Java的虚拟机实现版本 ",props.getProperty("java.vm.version"));
        infoMap.put("Java的虚拟机实现名称 ",props.getProperty("java.vm.name"));
        infoMap.put("操作系统的名称 ",props.getProperty("os.name"));
        infoMap.put("操作系统的构架 ",props.getProperty("os.arch"));
        infoMap.put("操作系统的版本 ",props.getProperty("os.version"));
        infoMap.put("用户的账户名称 ",props.getProperty("user.name"));
    }
    public static double getCpuLoad(){
        return RunningStatus.osmxb.getSystemCpuLoad();
    }
    public static double getMemoryLoad(){
        double total = RunningStatus.osmxb.getTotalPhysicalMemorySize();
        double free = RunningStatus.osmxb.getFreePhysicalMemorySize();
        return free/total;
    }

    public static RunningStatus getRunningStatus(boolean info){
        RunningStatus runningStatus = RunningStatus.create();
        if (info){
            return runningStatus.setInfo(infoMap);
        }
        return runningStatus;
    }
}
